def month_before(a_time)
  a_time - 28 * 24 * 60 * 60
end

def header(start_svn_date, end_svn_date)
  "Changes between #{start_svn_date} and #{end_svn_date}:"
end

def subsystem_line(subsystem_name, change_count)
  image = image_for(change_count)
  text = text_for(change_count)
  "#{subsystem_name.ljust(14)} #{text.ljust(14)} #{image}"
end

def image_for(an_integer)
  if an_integer == 0
    "-"
  elsif an_integer < 3
    "*"
  else
    "*" *  (an_integer / 5.to_f).round
  end
end

def text_for(an_integer)
  (an_integer == 0)? "-" : "(#{an_integer} changes)"
end

def change_count_for(subsystem_name, start_date)
  extract_change_count_from(svn_log(subsystem_name, start_date))
end

def extract_change_count_from(log_text)
  lines = log_text.split("\n")
  dashed_lines = lines.find_all do | line |
    line.include?("----")
  end
  dashed_lines.length - 1
end

def svn_date(a_time)
  a_time.strftime("%Y-%m-%d")
end

def svn_log(subsystem_name, start_date)
  timespan = "--revision HEAD:{#{start_date}}"
  root = "http://localhost/svn/jiazhuang"
  `svn log #{timespan} #{root}/#{subsystem_name}`
end

def order_by_descending_change_count(lines)
  lines.sort do |one, another|
    - (churn_line_to_int(one) <=> churn_line_to_int(another))
  end
end

def churn_line_to_int(line)
  /\((\d+)\s+\w+\)/.match(line)[1].to_i
end

def interesting(lines)
  lines.find_all do | line |
    /\s\*+/.match(line)
  end
end

def rearrange(string)
  names = /(\w+), (\w+)( \w+)?/.match(string)
  last_name = names[1]
  first_name = names[2]
  middle_name = names[3] 
  middle_name.nil? ? "#{first_name} #{last_name}" : "#{first_name}#{middle_name[0,2]}. #{last_name}"
end

if $0 == __FILE__    #(1)
  subsystem_names = %w(jiazhuang.xlsx
                      moban.xls test  keting.docx wit*)
  start_date = svn_date(month_before(Time.local(2010, 7, 13) + 28*24*60*60))

  puts header(start_date,svn_date(Time.now))                   #(4)

  lines = subsystem_names.collect do | name |
    subsystem_line(name, change_count_for(name, start_date)) #(5)
  end

  puts order_by_descending_change_count(lines)
end
